package com.getpebble.android.config;

import android.annotation.TargetApi;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.net.Uri;
import android.os.Handler;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.framework.util.AssetUtil;
import com.getpebble.android.util.LocaleUtil;
import com.getpebble.android.util.UriUtil;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.ref.WeakReference;

public class BootConfig {
    public static final String TAG = BootConfig.class.getSimpleName();
    private static final Handler sHandler = new Handler();
    private static BootConfig sInstance = null;
    JsonConfigHolder mConfigHolder = null;
    ContentObserver mContentObserver = new ContentObserver(sHandler) {
        public boolean deliverSelfNotifications() {
            return super.deliverSelfNotifications();
        }

        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }

        @TargetApi(16)
        public void onChange(boolean selfChange, Uri uri) {
            BootConfig.this.handleChange();
        }
    };
    WeakReference<Context> mContext = null;

    String getDefaultConfigString() {
        try {
            Context context = (Context) this.mContext.get();
            if (context != null) {
                return AssetUtil.getFileAsString(context, "default_boot_config.json");
            }
        } catch (IOException e) {
            Trace.error(TAG, e.getMessage(), e);
        }
        return null;
    }

    void handleChange() {
        String configString = getDefaultConfigString();
        Context context = (Context) this.mContext.get();
        if (context == null) {
            Trace.warning(TAG, "handleChange: context is null");
            return;
        }
        Cursor cursor = context.getContentResolver().query(PblContentProviderUtil.getTableUri("boot_config"), null, null, null, "_date_created DESC");
        if (cursor == null || !cursor.moveToFirst()) {
            Trace.error(TAG, "Failed to query data, defaulting!");
        } else {
            try {
                configString = cursor.getString(cursor.getColumnIndex("config_json"));
            } catch (CursorIndexOutOfBoundsException cioe) {
                Trace.error(TAG, cioe.getMessage(), cioe);
            }
        }
        if (cursor != null) {
            cursor.close();
        }
        if (configString != null) {
            Gson gson = new Gson();
            try {
                this.mConfigHolder = (JsonConfigHolder) gson.fromJson(configString, JsonConfigHolder.class);
            } catch (Exception e) {
                Trace.error(TAG, "Failed to marshall the boot config; defaulting", e);
                this.mConfigHolder = (JsonConfigHolder) gson.fromJson(getDefaultConfigString(), JsonConfigHolder.class);
            }
        }
    }

    private BootConfig(Context context) {
        this.mContext = new WeakReference(context);
        handleChange();
        context.getContentResolver().registerContentObserver(PblContentProviderUtil.getTableUri("boot_config"), true, this.mContentObserver);
    }

    public static BootConfig createInstance(Context context) throws IllegalArgumentException {
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        if (sInstance == null) {
            sInstance = new BootConfig(context);
        }
        return sInstance;
    }

    public static BootConfig getInstance() throws IllegalStateException {
        if (sInstance != null) {
            return sInstance;
        }
        Trace.error(TAG, "Failed to fetch instance!");
        throw new IllegalStateException("'sInstance' is null!  Please create it first.");
    }

    public String getAppStoreWatchAppsUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.appstore_watchapps;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAppStoreWatchFacesUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.appstore_watchfaces;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAuthenticationSignUpUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.authentication_sign_up;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAuthenticationSignInUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.authentication_sign_in;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAppStoreApplicationUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.appstore_application;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAppStoreDeveloperAppsUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.appstore_developer_apps;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getTermsAndConditionsUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.authentication_terms_and_conditions;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getOnboardingMigrateUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.onboarding_migrate;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAppUuidMigrateUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.links.apps_uuid_upgrades;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getOnboardingGetSomeAppsUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.onboarding_get_some_apps;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getSupportFAQUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.support_faq;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getSupportSuggestSomethingUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.support_suggest_something;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getSupportNotificationHelpUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.support_actionable_notifications == null ? "http://help.getpebble.com/customer/en/portal/articles/1819783" : this.mConfigHolder.config.webviews.support_actionable_notifications;
        } else {
            throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
        }
    }

    public String getSupportCommunityUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.support_community;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getSupportGettingStartedUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.webviews.support_getting_started;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getLockerUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.links.users_app_locker;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getLanguagesUrl() throws IllegalStateException {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.links.i18n_language_packs;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getSupportRequestSubject() throws IllegalStateException {
        if (this.mConfigHolder == null) {
            throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
        } else if (this.mConfigHolder.config == null || this.mConfigHolder.config.support_request == null) {
            return null;
        } else {
            return this.mConfigHolder.config.support_request.subject;
        }
    }

    public String getSupportRequestEmailAddress() throws IllegalStateException {
        if (this.mConfigHolder == null) {
            throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
        } else if (this.mConfigHolder.config == null || this.mConfigHolder.config.support_request == null) {
            return null;
        } else {
            return this.mConfigHolder.config.support_request.email;
        }
    }

    public String getBootConfigUrl() {
        String bootConfigUrl;
        Trace.debug(TAG, "getBootConfigUrl()");
        if (this.mConfigHolder != null) {
            bootConfigUrl = this.mConfigHolder.config.href;
        } else {
            bootConfigUrl = getFallbackBootUrl();
        }
        return appendLocaleToUrl(bootConfigUrl);
    }

    static String getFallbackBootUrl() {
        Trace.error(TAG, "Using fallback boot config URL: https://boot.getpebble.com/api/config/android/v1/4?");
        return "https://boot.getpebble.com/api/config/android/v1/4?";
    }

    public static String appendLocaleToUrl(String bootConfigUrl) {
        return UriUtil.stripQueryParameter(Uri.parse(bootConfigUrl), "locale").buildUpon().appendQueryParameter("locale", LocaleUtil.getCurrentLocaleTag()).build().toString();
    }

    public String getRemoteDeviceAnalytics() {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.links.remote_device_analytics;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getAuthenticationMeUrl() {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.links.authentication_me;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getUsersMeUrl() {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.links.users_me;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getDeveloperConnectionProxyUrl() {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.developer.ws_proxy_url;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getKeenProjectId() {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.keen_io.project_id;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public String getKeenWriteKey() {
        if (this.mConfigHolder != null) {
            return this.mConfigHolder.config.keen_io.write_key;
        }
        throw new IllegalStateException("There is no config holder! [mConfigHolder=null]");
    }

    public void catBootConfigToStream(PrintStream printStream) {
        printStream.println(this.mConfigHolder);
    }
}
